package com.hx.annotation.example;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author jxlgcmh
 * @date 2020-08-16 16:31
 * @description format方法
 */
public class SimpleFormat {
    public static String format(Object object) {
        try {
            Class<?> clazz = object.getClass();
            StringBuilder sb = new StringBuilder();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                Label label = field.getAnnotation(Label.class);
                // 获取label的名称
                String name = label != null ? label.value() : field.getName();
                Object value = field.get(object);
                if (value != null && field.getType() == Date.class) {
                    value = formatDate(field, value);
                }
                sb.append(name + ":" + value + "\n");
            }
            return sb.toString();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private static Object formatDate(Field field, Object value) {
        Format format = field.getAnnotation(Format.class);
        if (format != null) {
            DateFormat dateFormat = new SimpleDateFormat(format.pattern());
            dateFormat.setTimeZone(TimeZone.getTimeZone(format.timezone()));
            return dateFormat.format(value);
        }
        return value;
    }
}

